package com.base.cn.platform.os.controller.order.order;

import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.file.FileDownloadUtil;
import com.base.cn.platform.os.common.utils.order.OrderStatus;
import com.base.cn.platform.os.common.utils.order.ShopType;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.controller.order.order.utils.OrderExportExcelUtils;
import com.base.cn.platform.os.entity.order.order.Order;
import com.base.cn.platform.os.entity.order.order.OrderDetails;
import com.base.cn.platform.os.entity.order.order.OrderDetailsCondition;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.service.course.cou.buy.CourseBuyRecordService;
import com.base.cn.platform.os.service.order.order.OrderDetailsBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 订单流水接口
 *
 * @author s.li
 * @create 2018-05-15-14:10
 */
@RestController
@RequestMapping("/manage/order")
public class OrderDetailsController {
    @Autowired
    private OrderDetailsBiz orderDetailsBiz;
    @Autowired
    private CourseBuyRecordService courseBuyRecordService;

    /**
     * 查询订单列表
     * @param orderDetailsCondition 查询条件
     * @return
     */
    @RequestMapping("/findOrderDetailsList")
    public List<OrderDetails> findOrderDetailsList(@RequestBody OrderDetailsCondition orderDetailsCondition){
        return orderDetailsBiz.findOrderDetailsList(orderDetailsCondition,false,false,false);
    }

    /**
     * 分页查询订单流水数据
     * @param condition 查询条件
     * @param setUserData 是否设置用户数据
     * @param setShopData 是否设置商品数据
     * @param setOrderBook 是否设置图书订单扩展数据
     * @return PageInfo<OrderDetails>
     */
    @RequestMapping("/findOrderDetailsPage")
    public PageInfo<OrderDetails> findOrderDetailsPage(@RequestBody OrderDetailsCondition condition,
                                                       @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage,
                                                       @RequestParam("setUserData") boolean setUserData,
                                                       @RequestParam("setShopData") boolean setShopData,
                                                       @RequestParam("setOrderBook") boolean setOrderBook){
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        return orderDetailsBiz.findOrderDetailsPage(condition,page,setUserData,setShopData,setOrderBook);
    }

    /**
     * 通过ID，查询流水数据
     * @param id 流水ID
     * @param setUserData  是否设置用户数据
     * @param setShopData 是否设置商品数据
     * @param setOrderBook 是否设置图书订单扩展数据
     * @return OrderDetails
     */
    @RequestMapping("/findOrderDetailsInfo")
    public OrderDetails findOrderDetailsInfo(@RequestParam("id")BigDecimal id,
                                             @RequestParam("setUserData") boolean setUserData,
                                             @RequestParam("setShopData") boolean setShopData,
                                             @RequestParam("setOrderBook") boolean setOrderBook){
        return orderDetailsBiz.findOrderDetailsById(id,setUserData,setShopData,setOrderBook);
    }

    /**
     * 修改订单流水状态
     * @param sysUserId 管理员ID
     * @param id 流水ID
     * @param detailsStatus 状态
     * @return Map<String,Object>
     */
    @RequestMapping("/updateOrderDetailsStatus")
    public Map<String,Object> updateOrderDetailsStatus(@RequestParam("sysUserId") BigDecimal sysUserId,
                                                       @RequestParam("id") BigDecimal id,
                                                       @RequestParam("detailsStatus") String detailsStatus) throws Exception{
        OrderDetails details = orderDetailsBiz.findById(id);
        if(ObjectUtils.isEmpty(details)){
            return ResultUtil.ERROR("流水数据不存在");
        }
        if(detailsStatus.equals(OrderStatus.REFUND)){
            if(!details.getShopType().equals(ShopType.ORDER_SHOP_COURSE)
                    && !details.getShopType().equals(ShopType.ORDER_SHOP_BOOK)
                    && !details.getShopType().equals(ShopType.ORDER_SHOP_MEMBER)){
                return ResultUtil.ERROR("订单流水购买的商品不可退费");
            }
            courseBuyRecordService.updateRecordCourseStatus(details.getOrderId(),OrderStatus.REFUND);
        }
        //关闭流水课程
        if(detailsStatus.equals(OrderStatus.CLOSE)){
            if(!details.getShopType().equals(ShopType.ORDER_SHOP_COURSE) && !details.getShopType().equals(ShopType.ORDER_SHOP_MEMBER)){
                return ResultUtil.ERROR("该订单流水包含的商品不可以关闭");
            }
            if(!details.getDetailStatus().equals(OrderStatus.SUCCESS)){
                return ResultUtil.ERROR("当前状态的订单流水不可以关闭");
            }

        }
        if(detailsStatus.equals(OrderStatus.COURSE)){
            if(!details.getShopType().equals(ShopType.ORDER_SHOP_COURSE)){
                return ResultUtil.ERROR("该订单流水包含的商品非课程商品，不可延期");
            }
        }
        details.setDetailStatus(detailsStatus);
        //修改状态
        orderDetailsBiz.updateOrderDetailsStatus(details,sysUserId);
        return ResultUtil.SUCCESS("操作成功");
    }

    /**
     * 获取购买课程的用户Ids
     * @param courseIds
     * @return
     */
    @RequestMapping("/queryBuyCourseUserCountByCourseIds")
    public Map<BigDecimal,String> queryBuyCourseUserCountByCourseIds(String courseIds){
        return orderDetailsBiz.queryBuyCourseUserCount(courseIds);
    }


    /**
     *可设置 数据显示的数量
     * @param condition 查询条件
     * @param pageSize 数据显示数量
     * @param setUserData 是否设置用户数据
     * @param setShopData 是否设置商品数据
     * @param setOrderBook 是否设置图书订单扩展数据
     * @param setOrder 是否设置订单扩展数据
     * @return
     */
    @RequestMapping("/findOrderDetailsSpecialPage")
    public PageInfo<OrderDetails> findOrderDetailsSpecialPage(@RequestBody OrderDetailsCondition condition,
                                                          @RequestParam(value = "currentPage",required = false,defaultValue = "1") int currentPage,
                                                              @RequestParam(value = "pageSize",required = false,defaultValue = "10") int pageSize,
                                                          @RequestParam("setUserData") boolean setUserData,
                                                            @RequestParam("setShopData") boolean setShopData,
                                                         @RequestParam("setOrderBook") boolean setOrderBook,
                                                              @RequestParam("setOrder") boolean setOrder){
        Pagination page = new Pagination();
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        return orderDetailsBiz.findOrderDetailsSpecialPage(condition,page,setUserData,setShopData,setOrderBook,setOrder);
    }


    /**
     *可设置 数据显示的数量
     * @param condition 查询条件
     * @param pageSize 数据显示数量
     * @return
     */
    @RequestMapping("/downloadExcelOrdersDetailsList")
    public ResponseEntity<byte[]> downloadExcelOrdersDetailsList(@RequestBody OrderDetailsCondition condition,
                                                              @RequestParam(value = "pageSize") int pageSize,@RequestParam("distinguish") String distinguish) throws Exception {
        String[] heads =null;
        String expName ="";
        if(distinguish.equals("SALES")){

            heads  = new String[]{"ID", "对应订单号",
                    "订单类型", "购买商品", "下单用户昵称", "下单用户手机号",
                    "支付时间", "支付方式", "商品原价", "优惠减额", "活动减额",
                    "支付金额", "支付状态"};
            expName ="销售记录数据";
        }
        else if(distinguish.equals("REFUND")){
            heads  = new String[]{"ID", "对应订单号",
                    "订单类型", "购买商品", "下单用户昵称", "下单用户手机号",
                    "支付时间", "支付方式", "商品原价", "优惠减额", "活动减额",
                    "支付金额", "支付状态","退费金额"};
            expName ="退费记录数据";
        }
        return exportOrderXls(condition,pageSize,heads,expName,distinguish);
    }



    /**
     * 导出订单数据列表
     * @param condition 查询条件
     * @param pageSize 数据数量
     */
    private ResponseEntity<byte[]> exportOrderXls(OrderDetailsCondition condition, int pageSize, String[] heads,String expName,String distinguish) throws Exception {
        //生成文件的容器
        List<Map<String,Object>> srcFile = new ArrayList<>();
        //文件名
        expName = expName+System.currentTimeMillis();
        //获取数据
        PageInfo<OrderDetails> orderDetailsSpecialPage = this.findOrderDetailsSpecialPage(condition, 1, pageSize, true, false, false, true);
        if(ObjectUtils.isNotEmpty(orderDetailsSpecialPage.getList())){
            //每2000数据一个execl，如果页数大于1循环生成
            if(orderDetailsSpecialPage.getPages()>=1){
                for(int i=1;i<=orderDetailsSpecialPage.getPages();i++){
                    if(i>1){
                        orderDetailsSpecialPage = this.findOrderDetailsSpecialPage(condition, i, pageSize, true, false, false, true);
                    }
                    OrderExportExcelUtils.generateFile( getData(orderDetailsSpecialPage.getList(),distinguish),heads,expName+"_"+i+".xls",srcFile);
                }
            }
        }
        return FileDownloadUtil.createRar(srcFile,expName);
    }



    /**
     *
     * @param orderList 数据
     * @param distinguish 区分导出的是销售的数据还是退费的数据（SALES/REFUND）
     * @return
     */
    private List<List<String>> getData(List<OrderDetails> orderList,String distinguish){
        List<List<String>> data = new ArrayList<>();

        orderList.forEach((v)->{
            CusUser user = v.getUser();
            Order order = v.getOrder();

            data.add(Arrays.asList(
                    v.getId().toString(),
                    v.getOrderNo(),
                    ObjectUtils.isNotEmpty(order)?OrderExportExcelUtils.backOrderType(order.getOrderType()):"",
                    ObjectUtils.isNotEmpty(v.getShopName())?v.getShopName():"",
                    ObjectUtils.isNotEmpty(user)?user.getNickname():"",
                    ObjectUtils.isNotEmpty(user)&&ObjectUtils.isNotEmpty(user.getMobile())?user.getMobile():"",
                    ObjectUtils.isNotEmpty(v.getPayTime())? DateUtils.format(v.getPayTime()):"",
                    OrderExportExcelUtils.backPaymentType(v.getPayType()),
                    v.getPrice().toString(),
                    v.getYhPrice().toString(),
                    v.getActivityPrice().toString(),
                    v.getRealPrice().toString(),
                    OrderExportExcelUtils.backOrderStatus( v.getDetailStatus()),
                    distinguish.equals("REFUND")?v.getRealPrice().toString():null

            ));

        });
        return  data;
    }


}


